/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    long long kthLargestLevelSum(TreeNode *root, int k)
    {
        queue<TreeNode *> q;
        q.push(root);
        vector<long long> layerSums;
        while (!q.empty())
        {
            int layerSize = q.size();
            long long layerSum = 0;
            for (int _ = 0; _ < layerSize; ++_)
            {
                TreeNode *node = q.front();
                q.pop();
                if (node->left != nullptr)
                {
                    q.push(node->left);
                }
                if (node->right != nullptr)
                {
                    q.push(node->right);
                }
                layerSum += node->val;
            }
            layerSums.push_back(layerSum);
        }
        if (layerSums.size() < k)
        {
            return -1;
        }
        sort(layerSums.rbegin(), layerSums.rend());
        return *(layerSums.begin() + k - 1);
    }
};